package org.shilong.UI.OAuth;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.shilong.MContext.Json.JSonContext;
import org.shilong.MContext.WebRequest.WebRequestContext;
import org.shilong.Model.FriendModel;
import org.shilong.UI.R;
import org.shilong.UI.businessCard.CreateBusinessCardFrame;
import org.shilong.UI.register.RegisterFrame;
import org.shilong.Utility.IntentUtility;
import org.shilong.Utility.ProgressDialogUtility;
import org.shilong.Utility.SharedPreferenceUtility;
import org.shilong.Utility.ToastUtility;
import org.shilong.Utility.constants.APIConstants;
import org.shilong.Utility.constants.WeiboConstants;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;

import com.weibo.net.Oauth2AccessTokenHeader;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

public class OAuth2Frame extends Activity {

	private String ac_name,ac_pwd, uid, a_token, a_expires_in;

	private AlertDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView( R.layout.layout_oauth2_content );

		Bundle bun = getIntent().getExtras();

		ac_name = bun.getString( "a_name" );
		ac_pwd = bun.getString( "a_pwd" );
		a_token = bun.getString( "a_token" );
		a_expires_in = bun.getString( "a_expires_in" );

		System.out.println( "=======>ac_name:" + ac_name );
		System.out.println( "=======>ac_pwd:" + ac_pwd );
		System.out.println( "=======>a_token:" + a_token );
		System.out.println( "=======>a_expires_in:" + a_expires_in );

		NewInsertUserTask task = new NewInsertUserTask( OAuth2Frame.this );
		task.execute();
	}

	/**
	 * 新建用户task
	 * @author cesc
	 *
	 */
	private class NewInsertUserTask extends AsyncTask<String, String, String>{

		private Context con;

		private NewInsertUserTask( Context mContext){

			this.con = mContext;

		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub

			System.out.println( "注册的结果是:" + result );

			if( result.equals( "this_account_registed_successed" ) ){


				SharedPreferenceUtility.saveAccessTokenAndExpiresToSharedPreference( a_token, a_expires_in, ac_name, uid, OAuth2Frame.this );

				System.out.println( "注册信息存入成功..." );

				ProgressDialogUtility.cancelDialog();

				ToastUtility.showToast(OAuth2Frame.this, "注册成功..." );

				//	跳转到创建名片屏
				IntentUtility.goNextFrame(OAuth2Frame.this, CreateBusinessCardFrame.class, null );

				OAuth2Frame.this.finish();

			}else if( result.equals( "this_account_already_registed" )){

				AlertDialog.Builder builder = new AlertDialog.Builder( OAuth2Frame.this );

				builder.setMessage( ac_name + "已被注册过" );

				builder.setPositiveButton( "重新注册", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {

						arg0.dismiss();
						IntentUtility.goNextFrame( OAuth2Frame.this, RegisterFrame.class, null );
						OAuth2Frame.this.finish();

					}
				});

				dialog = builder.create();
				dialog.show();
			}

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			ProgressDialogUtility.showDialog( con, "注册中.." );

		}

		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub

			String rlt  = "error";

			WeiboParameters params =  new WeiboParameters();

			params.add( "source", WeiboConstants.APIKEY );

			Utility.setAuthorization(new Oauth2AccessTokenHeader());  //	加上之后就不报出现过期的等异常了

			try {
				/*获取微博uid 并且注册*/

				uid = Weibo.getInstance().request(con, APIConstants.GET_UID, params, Utility.HTTPMETHOD_GET,Weibo.getInstance().getAccessToken() );
				uid = ( String )JSonContext.createInstance( JSonContext.TYPE_GET_UID ).getJsonRlt( uid );

				rlt = WebRequestContext.createInstance( WebRequestContext.TYPE_REGISTER ).getWebRequestRlt( ac_name, ac_pwd, uid, a_token, a_expires_in );

				if( rlt.equals("this_account_registed_successed") ){

					System.out.println("此账号可以注册,开始获取用户的互粉列表并注册到服务器中 ");
					
					WeiboParameters wp = new WeiboParameters();
					wp.add("uid", uid);
					
					//获取互粉好友
					String friendsRlt = Weibo.getInstance().request(OAuth2Frame.this, APIConstants.GET_FRIEND_DIRECTLY,
							wp, Utility.HTTPMETHOD_GET,
							Weibo.getInstance().getAccessToken());

					System.out.println("获取互粉好用信息的是"+ friendsRlt );
					
					/*List<FriendModel> friendList = new ArrayList<FriendModel>();

					friendList = getIdsList(friendsRlt);

					String result = "";

					result = getJsonRlt2(friendList);
					
					System.out.println( "封装的json值是:" + result );
					String add_rtl = WebRequestContext.createInstance( WebRequestContext.TYPE_ADD_WEIBO_FRIEND ).getWebRequestRlt( ac_name,result );

					System.out.println( "加入好友结果值是：" + add_rtl);*/
					
					
					String result = "";
					result = getFriendRltJson(friendsRlt);
					
					System.out.println("封装的json："+ result );
					String add_rtl = WebRequestContext.createInstance( WebRequestContext.TYPE_ADD_WEIBO_FRIEND ).getWebRequestRlt( ac_name,result );

					System.out.println( "加入好友结果值是：" + add_rtl);
					
				}



			}catch (Exception e) {
				throw new RuntimeException( e );
			}

			return rlt;
		}


		
		/**
		 * 直接获取互粉好友的信息
		 * @param rlt
		 * @return
		 * @throws JSONException
		 */
		private String getFriendRltJson( String rlt) throws JSONException{
			
			JSONObject rltObj = new JSONObject();
			JSONArray  rltArray = new JSONArray();
			
			
			JSONObject obj = new JSONObject(rlt);
			JSONArray arr = obj.getJSONArray( "users" );
			
			for( int i  = 0; i < arr.length(); i++ ){
				
				JSONObject oo = arr.getJSONObject(i);
				
				JSONObject  rltOO = new JSONObject();
				
				rltOO.put("desc", oo.getString("description") );
				rltOO.put("location", oo.getString("location"));
				rltOO.put("image_url", oo.getString("profile_image_url"));
				rltOO.put("screen_name", oo.getString("screen_name") );
				rltOO.put("weibo_id", oo.getString("id") );
				
				
				/*oo.put("desc", friendModel.getDescription());
				oo.put("location", friendModel.getLocation());
				oo.put("image_url", friendModel.getProfile_image_url() + ".jpg" );
				oo.put("screen_name", friendModel.getScreen_name());
				oo.put("weibo_id", friendModel.getWeibo_id());*/
				
				rltArray.put( rltOO );
				
			}
			
			rltObj.put("rlt",  rltArray );
			
			return  rltObj.toString();
		}
		
		
		/**
		 * 获取用户ID
		 * @param rlt
		 * @return
		 */
		private List<FriendModel> getIdsList( String rlt ){

			List<FriendModel> friList = new ArrayList<FriendModel>();
			
			try {
				JSONObject obj = new JSONObject(rlt);
				
				String IDARR = obj.getString("ids");
				

				IDARR  = IDARR.replace("[", "");
				IDARR  = IDARR.replace("]", "");

				String[] arr = IDARR.split(",");

				for (String string : arr) {

					Weibo mWeibo = Weibo.getInstance();

					WeiboParameters params = new WeiboParameters();
					params.add( "uid", string );

					Utility.setAuthorization( new  Oauth2AccessTokenHeader() );
					
					String re = mWeibo.request( OAuth2Frame.this , "https://api.weibo.com/2/users/show.json", params, Utility.HTTPMETHOD_GET, mWeibo.getAccessToken());

					JSONObject oo = new JSONObject( re );

					FriendModel model = new FriendModel();

					model.setWeibo_id( oo.getString("id"));
					model.setScreen_name( oo.getString("screen_name"));
					model.setProfile_image_url( oo.getString("profile_image_url"));
					model.setLocation( oo.getString(  "location"  ) );
					model.setDescription( oo.getString( "description" ));
					
					friList.add(model);
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			/*String IDARR = obj.getString("ids");

			IDARR  = IDARR.replace("[", "");
			IDARR  = IDARR.replace("]", "");

			String[] arr = IDARR.split(",");

			for (String string : arr) {

				Weibo mWeibo = Weibo.getInstance();

				WeiboParameters params = new WeiboParameters();
				params.add( "uid", string );

				Utility.setAuthorization( new  Oauth2AccessTokenHeader() );

				try {
					String re = mWeibo.request( OAuth2Frame.this , "https://api.weibo.com/2/users/show.json", params, Utility.HTTPMETHOD_GET, mWeibo.getAccessToken());

					JSONObject oo = new JSONObject( re );

					FriendModel model = new FriendModel();

					model.setWeibo_id( oo.getString("id"));
					model.setScreen_name( oo.getString("screen_name"));
					model.setProfile_image_url( oo.getString("profile_image_url"));
					model.setLocation( oo.getString(  "location"  ) );
					model.setDescription( oo.getString( "description" ));
					
					friList.add(model);
				} catch (WeiboException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
*/
			return friList;

		}
	}


	/**
	 * 获取json字符串
	 * @param list
	 * @return
	 * @throws JSONException
	 */
	private String getJsonRlt2( List<FriendModel> list ) throws JSONException{
		
		JSONObject obj = new JSONObject();
		
		JSONArray arr = new JSONArray();
		
		Iterator<FriendModel> it = list.iterator();
		
		while (it.hasNext()) {
			FriendModel friendModel = (FriendModel) it.next();
			
			JSONObject oo = new JSONObject();
			
			
			
			oo.put("desc", friendModel.getDescription());
			oo.put("location", friendModel.getLocation());
			oo.put("image_url", friendModel.getProfile_image_url() + ".jpg" );
			oo.put("screen_name", friendModel.getScreen_name());
			oo.put("weibo_id", friendModel.getWeibo_id());
			
			arr.put( oo );
			
		}
		
		
		obj.put("rlt", arr);
		
		System.out.println( "rlt2=====>" + obj.toString());
		
		return obj.toString();
	}
}
